package com.xyhuo.leetcode.y2025;

public class ComputeArea {

    public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
        if (((ax1 < bx1 && ax2 < bx1) || (bx1 < ax1 && bx2 < ax1)) || ((ay1 < by1 && ay2 < by1) || (by1 < ay1 && by2 < ay1))) {
            int areaA = area(ax1, ay1, ax2, ay2);
            int areaB = area(bx1, by1, bx2, by2);

            return areaA + areaB;
        }

        int minX = Math.min(ax1, bx1);
        int maxX = Math.max(ax2, bx2);

        int minY = Math.min(ay1, by1);
        int maxY = Math.max(ay2, by2);

        int area = area(minX, minY, maxX, maxY);
        area -= emptyArea(ax1, ay1, bx1, by1, ax1, ay1, ax2, ay2, bx1, by1, bx2, by2);
        area -= emptyArea(ax1, ay2, bx1, by2, ax1, ay1, ax2, ay2, bx1, by1, bx2, by2);
        area -= emptyArea(ax2, ay2, bx2, by2, ax1, ay1, ax2, ay2, bx1, by1, bx2, by2);
        area -= emptyArea(ax2, ay1, bx2, by1, ax1, ay1, ax2, ay2, bx1, by1, bx2, by2);

        return area;
    }

    private int area(int x1, int y1, int x2, int y2) {
        return Math.abs(x1 - x2) * Math.abs(y1 - y2);
    }

    private int emptyArea(int x1, int y1, int x2, int y2, int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
        int area = area(x1, y1, x2, y2);
        float middleX = ((float) (x1 + x2)) / 2;
        float middleY = ((float) (y1 + y2)) / 2;
        if (middleX <= ax2 && middleX >= ax1 && middleY <= ay2 && middleY >= ay1) {
            return 0;
        }
        if (middleX <= bx2 && middleX >= bx1 && middleY <= by2 && middleY >= by1) {
            return 0;
        }
        return area;
    }

    public static void main(String[] args) {
        ComputeArea c = new ComputeArea();
        int i = c.computeArea(-3, 0, 3, 4, 0, -1, 9, 2);
        System.out.println(i);
    }
}
